import socket
import threading

# 处理客户端连接的函数
def handle_client(client_socket, client_address):
    try:
        while True:
            # 接收客户端消息
            data = client_socket.recv(1024)
            if not data:
                break
            message = data.decode('utf-8')
            print(f"Received from {client_address}: {message}")
            # 回复消息给客户端
            client_socket.sendall(data)
    except Exception as e:
        print(f"Error handling client {client_address}: {e}")
    finally:
        # 关闭客户端连接
        client_socket.close()
        print(f"Connection with {client_address} closed")

def main():
    # 创建 TCP 套接字
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # 绑定地址和端口
    server_address = ('0.0.0.0', 25322)
    server_socket.bind(server_address)
    # 开始监听，允许最大 5 个连接
    server_socket.listen(5)
    print(f"Server is listening on {server_address}")

    try:
        while True:
            # 接受客户端连接
            client_socket, client_address = server_socket.accept()
            print(f"Accepted connection from {client_address}")
            # 为每个客户端创建一个新线程处理连接
            client_thread = threading.Thread(target=handle_client, args=(client_socket, client_address))
            client_thread.start()
    except KeyboardInterrupt:
        print("Server shutting down...")
    finally:
        # 关闭服务器套接字
        server_socket.close()

if __name__ == "__main__":
    main()
    